#表单 add by Luxh
Form = require('../models/form').Form
common_util = require('../services/common_util')
util = require("util")
dataPage = require('../services/dataPage').queryPage
resErr = require('./util').resErr
ud = require('underscore')

exports.form_get = (req,res) ->
  form_code = req.params.form_code
  if !form_code
    resErr(res,"表单编码不能为空！")
  else
    Form.find {form_code:form_code},(err,docs) ->
      if err
        resErr(res,err)
      else
        return res.json(docs[0]) if docs.length == 0 
        result = docs[0]
        result.fields =  ud.sortBy result.fields,(field)->
          return field.order
        return res.json result


exports.form_list = (req,res) ->
  params = {}
  #相当于sql里面like的写法
  params.form_code = {'$regex': req.param("form_name")}  unless !req.param("form_name")
  params.form_code = {'$regex': req.param("form_code")}  unless !req.param("form_code")
  sorts = {_id:-1}
  dataPage Form,params,sorts,req.param("pageSize") or req.param("limit"),req.param("pageNum") or req.param("page"),(err,results) ->
    if err
      resErr(res,err)
    else
      res.json(results)


exports.form_add= (req,res) ->
  form_code = common_util.trim(req.param("form_code"))
  if !form_code
    res.json({'flag':'error','msg':'表单编码不能为空！'})
  else
    Form.count {form_code:form_code},(err,count) ->
      if err
        resErr(res,err)
      else
        if count > 0
          res.json({'flag':'error','msg':'表单编码已存在！'})
        else
          form = new Form
          form.add req,(err,doc) ->
            if err
              resErr(res,err)
            else
              res.json({'flag':'success'})



exports.form_detail = (req,res) ->
  _id = req.param('_id')
  if !_id
    res.json({'success':'false','err_msg':'编码不得为空'})
  else
    Form.findById _id, (err,result) ->
      if err
        resErr(res,err)
      else
        res.json(result)


exports.form_edit = (req,res) ->
  _id = req.param("_id")
  if !_id
    res.json({'flag':'error','msg':'编码不得为空！'})
  else
    form_code = common_util.trim(req.param("form_code"))
    if !form_code
      res.json({'flag':'error','msg':'表单编码不能为空！'})
    else
      Form.count {"_id":{"$ne":_id},"form_code":form_code},(err,count) ->
        if err
          resErr(res,err)
        else
          if count > 0
            res.json({'flag':'error','msg':'表单编码已存在！'})
          else
            Form.findById _id,(err,role) ->
              if err
                resErr(res,err)
              else
                role.form_code = form_code
                role.form_name = req.param("form_name")
                role.form_desc = req.param("form_desc")
                role.save (err) ->
                  if err
                    console.error(err)
                    res.json({'flag':'error','msg':err})
                  else
                    res.json({'flag':'success'})


exports.form_del = (req,res) ->
  if !req.param('_id')
    resErr(res,'编码不得为空')
  else
    _id = req.param('_id')
    Form.findByIdAndRemove _id,(err)->
      if err
        resErr res,err
      else
        res.json({'success':true})


exports.form_field_list = (req,res) ->
  if !req.param('form_id')
    resErr(res,'编码不得为空')
  else
    form_id = req.param('form_id')
    Form.findById form_id, (err,form) ->
      if err
        resErr res,err
      else
        if !form.fields or form.fields.length <1
          results = {};
          limit = req.param("pageSize") or req.param("limit")
          results.pageSize = limit
          results.pageNum = req.param("pageNum") or req.param("page")
          results.pageCount = 0;
          results.count = 0
          results.data = []
          res.json(results)
        else
          count = form.fields.length
          limit = req.param("pageSize") or req.param("limit")
          results = {};
          results.pageSize = limit
          results.pageNum = req.param("pageNum") or req.param("page")
          results.pageCount = if(count % limit == 0 ) then count / limit else parseInt(count / limit) + 1;
          results.count = count          
          form.fields =  ud.sortBy form.fields,(field)->
            return field.order
          results.data = form.fields
          res.json(results)


exports.form_field_add = (req,res) ->
  if !req.param('form_id')
    resErr(res,'编码不得为空')
  else
    Form.findById req.param('form_id'), (err,form) ->
      if err
        res.json({'flag':'error','msg':err})
      else
        params = {}
        params.xtype = req.param('xtype')
        params.field_label = req.param('field_label')
        params.name = req.param('name')
        params.colspan = req.param('colspan')
        params.width = req.param('width')
        params.height = req.param('height')
        params.allow_blank = req.param('allow_blank')
        params.order = req.param('order')
        params.data_type = req.param('data_type')
        params.data_format = req.param('data_format')
        params.read_only = req.param('read_only')
        params.display_field = req.param('display_field')
        params.value_field = req.param('value_field')
        params.use_url = req.param("url") ? true : false
        params.url = req.param('url')
        params.items = req.param('items')
        params.cascade_field2 = req.param("cascade_field2")
        params.cascade_label2 = req.param("cascade_label2")
        params.url2 = req.param("url2")
        params.items2 = req.param("items2")
        params.cascade_field3 = req.param("cascade_field3")
        params.cascade_label3 = req.param("cascade_label3")
        params.url3 = req.param("url3")
        params.items3 = req.param("items3")
        
        form.fields.push params
        form.save (err) ->
          if err
            res.json({'flag':'error','msg':err})
          else
            res.json({'flag':'success'})


exports.form_field_detail = (req,res) ->
  _id = req.param('_id')
  if !_id
    res.json({'success':'false','err_msg':'编码不得为空'})
  else
    Form.find {"fields._id":_id},(err,form) ->
      if err
        resErr res,err
      else
        result = {}
        fields = form[0].fields
        for field in fields
          if _id == field._id.toString()
            result = field
            break
        res.json(result)


exports.form_field_edit = (req,res) ->
  if !req.param('_id')
    resErr(res,'编码不得为空')
  else
    params = {}
    params['fields.$.xtype'] = req.param('xtype')
    params['fields.$.field_label'] = req.param('field_label')
    params['fields.$.name'] = req.param('name')
    params['fields.$.colspan'] = req.param('colspan')
    params['fields.$.width'] = req.param('width')
    params['fields.$.height'] = req.param('height')
    params['fields.$.allow_blank'] = req.param('allow_blank')
    params['fields.$.order'] = req.param('order')
    params['fields.$.data_type'] = req.param('data_type')
    params['fields.$.data_format'] = req.param('data_format')
    params['fields.$.read_only'] = req.param('read_only')
    params['fields.$.display_field'] = req.param('display_field')
    params['fields.$.value_field'] = req.param('value_field')
    params['fields.$.use_url'] = req.param("url") ? true : false
    params['fields.$.url'] = req.param('url')
    params['fields.$.items'] = req.param('items')
    params['fields.$.updated_at'] = new Date
    params['fields.$.cascade_field2'] = req.param('cascade_field2')
    params['fields.$.cascade_label2'] = req.param('cascade_label2')
    params['fields.$.items2'] = req.param('items2')
    params['fields.$.url2'] = req.param('url2')
    params['fields.$.cascade_field3'] = req.param('cascade_field3')
    params['fields.$.cascade_label3'] = req.param('cascade_label3')
    params['fields.$.items3'] = req.param('items3')
    params['fields.$.url3'] = req.param('url3')

    console.log params
    Form.update {"fields._id":req.param('_id')}, {"$set":params},(err) ->
      if err
        res.json({'flag':'error','msg':err})
      else
        res.json({'flag':'success'})


exports.form_field_del = (req,res) ->
  if !req.param('_id')
    resErr(res,'编码不得为空')
  else
    Form.findOne {"fields._id":req.param('_id')},(err,form) ->
      if err
        res.json({'flag':'error','msg':err})
      else
        fields = form.fields
        for f in fields
          if f._id.toString() == req.param('_id')
            fields.pull f
            break
        form.markModified('fields')
        form.fields = fields
        form.save (err)->
          if err
            res.json({'flag':'error','msg':err})
          else
            res.json({'flag':'success'})





exports.form_search_field_list = (req,res) ->
  if !req.param('form_id')
    resErr(res,'编码不得为空')
  else
    form_id = req.param('form_id')
    Form.findById form_id, (err,form) ->
      if err
        resErr res,err
      else
        if !form.search_fields or form.search_fields.length <1
          results = {};
          limit = req.param("pageSize") or req.param("limit")
          results.pageSize = limit
          results.pageNum = req.param("pageNum") or req.param("page")
          results.pageCount = 0;
          results.count = 0
          results.data = []
          res.json(results)
        else
          count = form.search_fields.length
          limit = req.param("pageSize") or req.param("limit")
          results = {};
          results.pageSize = limit
          results.pageNum = req.param("pageNum") or req.param("page")
          results.pageCount = if(count % limit == 0 ) then count / limit else parseInt(count / limit) + 1;
          results.count = count
          results.data = form.search_fields
          res.json(results)

exports.form_search_field_add = (req,res) ->
  if !req.param('form_id')
    resErr(res,'编码不得为空')
  else
    name = req.param('name')
    is_like = req.param('is_like')
    Form.findById req.param('form_id'), (err,form) ->
      if err
        res.json({'flag':'error','msg':err})
      else
        flag = false
        for f in form.search_fields
          if name == f.name
            flag = true
            break
        if flag
          res.json({'flag':'error','msg':'该字段已添加，不能再次添加！'})
        else
          params = {}
          params.name = name
          params.is_like = is_like
          form.search_fields.push params
          form.save (err) ->
            if err
              res.json({'flag':'error','msg':err})
            else
              res.json({'flag':'success'})


exports.form_search_field_detail = (req,res) ->
  _id = req.param('_id')
  if !_id
    res.json({'success':'false','err_msg':'编码不得为空'})
  else
    Form.find {"search_fields._id":_id},(err,form) ->
      if err
        resErr res,err
      else
        result = {}
        search_fields = form[0].search_fields
        for field in search_fields
          if _id == field._id.toString()
            result = field
            break
        res.json(result)


exports.form_search_field_edit = (req,res) ->
  if !req.param('_id')
    resErr(res,'编码不得为空')
  else
    params = {}
    params['search_fields.$.name'] = req.param('name')
    params['search_fields.$.is_like'] = req.param('is_like')

    name = req.param('name')
    _id = req.param('_id')
    Form.findById req.param('form_id'), (err,form) ->
      if err
        res.json({'flag':'error','msg':err})
      else
        flag = false
        for f in form.search_fields
          if name == f.name and _id != f._id.toString()
            flag = true
            break
        if flag
          res.json({'flag':'error','msg':'该字段已添加，不能再次添加！'})
        else
          Form.update {"search_fields._id":req.param('_id')}, {"$set":params},(err) ->
            if err
              res.json({'flag':'error','msg':err})
            else
              res.json({'flag':'success'})

exports.form_search_field_del = (req,res) ->
  if !req.param('_id')
    resErr(res,'编码不得为空')
  else
    Form.update {},{"$pull":{"search_fields":{"_id":req.param('_id')}}},(err) ->
      if err
        res.json({'flag':'error','msg':err})
      else
        res.json({'flag':'success'})